package com.yxq.mdt.app.modules.bottomsheet;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.modules.goodsdetail.bean.GoodsDetailBean;
import com.yxq.mdt.app.utils.MediaPlayerHelper;
import com.yxq.mdt.app.utils.MediaRecorderHelper;
import com.yxq.mdt.app.utils.WaveView;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by _SOLID
 * Date:2016/3/22
 * Time:14:32
 */
public class SoundVoiceBottomSheetDialogFragment extends BottomSheetDialogFragment implements View.OnClickListener {
    Unbinder unbinder;
    private static final int ACTION_RECORDING = 1;
    private static final int ACTION_NORMAL = 0;
    private static final int ACTION_COMMPLETE = 2;
    private static final int ACTION_PLAYING = 3;
    private static final int ACTION_PAUSE = 4;
    private TextView mTvRecorderTime;
    private ImageView mIvAction;
    private WaveView mWaveView;
    private RelativeLayout mRlBottom;
    private ImageView mIvSave;
    private ImageView mIvDelete;
    private int mCurrentActionState = ACTION_NORMAL;
    private MediaRecorderHelper mMediaRecorderHelper;
    //    private Thread mCountTimeThread;
    private int mTotalSecond = 0;
    private boolean mIsRecorder;
    CountDownTimer timer;
    String s;
    SoundVoiceBottomSheetDialogFragmentTime soundVoiceBottomSheetDialogFragmentTime;
    String TimeResult;
    //申请录音权限
    private static final int GET_RECODE_AUDIO = 1;
    private static String[] PERMISSION_AUDIO = {Manifest.permission.RECORD_AUDIO};

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置背景透明，才能显示出layout中诸如圆角的布局，否则会有白色底（框）
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme);

    }

    public boolean checkPermission3(Context context, String[] permissions) {

        for (String permission : permissions) {
            int per = ContextCompat.checkSelfPermission(context, permission);
            if (PackageManager.PERMISSION_GRANTED != per) {
                return false;
            }
        }
        return true;
    }

    public SoundVoiceBottomSheetDialogFragment(String s) {
        this.s = s;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_sound_recoder, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(view);
        return view;
    }

    public void setSoundVoiceBottomSheetDialogFragmentTime(SoundVoiceBottomSheetDialogFragmentTime s) {
        this.soundVoiceBottomSheetDialogFragmentTime = s;
    }

    public interface SoundVoiceBottomSheetDialogFragmentTime {
        void onclick(String time, String path);
    }

    public void initView(View itemView) {
        mTvRecorderTime = (TextView) itemView.findViewById(R.id.tv_recoder_time);
        mIvAction = (ImageView) itemView.findViewById(R.id.iv_action);
        mIvAction.setOnClickListener(this);
        mMediaRecorderHelper = new MediaRecorderHelper(getRecorderFilePath(itemView.getContext()));
        mIsRecorder = false;
    }

    public String getRecorderFilePath(Context context) {
        String path = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            path = context.getExternalCacheDir().getAbsolutePath();
        } else {
            path = context.getCacheDir().getAbsolutePath();

        }
        return path + File.separator + "Recorder";
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_action:
                switchActionState();
                break;
            default:
                break;
        }
    }

    /**
     * 切换ACTION状态
     */
    private void switchActionState() {
        mIsRecorder = false;
        if (mCurrentActionState == ACTION_NORMAL) {//录制中
            mCurrentActionState = ACTION_RECORDING;
            Glide.with(getContext()).load(R.drawable.play).into(mIvAction);
            //开始录音
            mMediaRecorderHelper.startRecord();
            mIsRecorder = true;
            //开启计时线程
            timer = new CountDownTimer(90000, 1000) {
                @Override
                public void onTick(long l) {
                    if (mIsRecorder) {
                        mTotalSecond++;
                        mTvRecorderTime.setText(getShowTime(mTotalSecond));
                    }
                    MediaPlayerHelper.realese();
                }

                @Override
                public void onFinish() {
                    //90秒之后
                    mMediaRecorderHelper.stopAndRelease();
                    soundVoiceBottomSheetDialogFragmentTime.onclick(TimeResult, mMediaRecorderHelper.getCurrentFilePath());
                    dismiss();

                }
            };
            timer.start();
        } else if (mCurrentActionState == ACTION_RECORDING) {//录制完成
            if (timer != null) {
                timer.cancel();
            }
            mMediaRecorderHelper.stopAndRelease();
            soundVoiceBottomSheetDialogFragmentTime.onclick(TimeResult, mMediaRecorderHelper.getCurrentFilePath());
            dismiss();
        }
    }

    //改变多少秒
    public String getShowTime(int countTime) {
        String result = "";
        if (countTime < 90) {
            result = countTime + "″";
            TimeResult = String.valueOf(countTime);
        } else {
            int minute = countTime / 60;
            int mod = countTime % 60;
            if (minute < 10) result += "0" + minute + ":";
            else {
                result += minute + ":";
            }
            if (mod < 10) result += "0" + mod;
            else {
                result += mod;
            }

        }
        return result;
    }


}
